package cn.kbyue.demo.websocketdemo.websocket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;

/**
 * @author XL
 * @version 0.1
 * @date 2022/6/10 21:26
 */
@Component
@Slf4j
@ServerEndpoint("/websocket")
public class WebsocketServer {

    private static int onlineCount = 0;

    private Session session;

    private String userId = "";

    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        this.userId = session.getId();

        incrementOnline();
        log.info(">> 新用户连接: {}, 当前在线人数: {}", userId, onlineCount);
    }

    @OnClose
    public void onClose(Session session) {
        log.info(">> 用户: {} 断开连接. 当前剩余人数: {}", userId, onlineCount);
        decreaseOnline();
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        log.info(">> 服务器接收 {} 消息: {}", userId, message);

        sendMessage(String.format(">> 服务器已收到你的消息: %s", message));
    }

    @OnError
    public void onError(Session session, Throwable error) {
        log.info(">>> 用户: {}, 错误: {}", userId, error.getMessage());
        error.printStackTrace();
    }

    private void sendMessage(String message) {
        try {
            this.session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static synchronized void incrementOnline() {
        WebsocketServer.onlineCount++;
    }

    private static synchronized void decreaseOnline() {
        WebsocketServer.onlineCount--;
    }

}
